#include "icache/still_footage.h"
#include "icache/still_image_id.h"
#include "icache/coordinator.h"
#include "imglib/io.h"
#include "mswin/file_dir.h"
#include "xml/stream.h"

namespace icache {

string still_footage::filepath() const
{
	return _fullpath;
}

item_id_sptr still_footage::frame_id(int frame)
{
	return still_image_id::create(_fullpath);
}

cached_image_sptr still_footage::get(int frame, nearby may_be_requested_later, bool wait)
{
	//wait=false is not supported due to absence of additional thread :(
	return _coordinator->get(frame_id(frame));
}

cached_image_sptr still_footage::try_get(int frame)
{
	return _coordinator->try_get(frame_id(frame));
}

icache::cache * still_footage::cache() const
{
	return _coordinator;
}

xml::stream & still_footage::serialize(xml::stream & s, string const & reference_path)
{
	xml::node & r = s.root();
	if (s.out()) {
		assert(is_open());
		r["type"] = "still";
		r["path"] = mswin::relative(_fullpath, reference_path);
	}
	else {
		if ((string)r["type"] != "still")
			throw exception("couldn't initialize Still Footage from XML stream");
		open(mswin::absolute(r["path"], reference_path));
	}
	return s;
}

string still_footage::description() const
{
	return string("image '") + _fullpath + "'";
}

int still_footage::size() const
{
	return 1;
}

int still_footage::first_frame_num() const
{
	return 0;
}

size_extent still_footage::dim() const
{
	return _dim;
}

bool still_footage::alpha_channel() const
{
	return _alpha;
}

fraction still_footage::fps() const
{
	return fraction(0,0); //invalid fraction
}

still_footage::still_footage(const string & filename, icache::coordinator * c)
{
	_coordinator = c;
	if (!filename.empty())
		open(filename);
}

still_footage::~still_footage()
{
}

void still_footage::open(const string & filename)
{
	string p = mswin::fullpath(filename);
	img::file_info info;
	if (!img::our_gdiplus_multireader().ping(p, &info))
		throw std::runtime_error(string("could not read file or unknown image format: ") + p);
	_fullpath = p;
	_dim = info.dim;
	_alpha = info.bit_count == 32;
}

} //namespace icache
